<template>
  <t-dialog
    v-model:show="selfVisible"
    position="right"
    :maximized="true"
    class="personnel-selector-popup"
    @before-show="onBeforeShow"
    @hide="onHide"
  >
    <div
      class="bg-white window-width window-height overflow-hidden flex flex-col select-none"
      :style="{
        maxHeight: 'calc(100% - env(safe-area-inset-bottom) - env(safe-area-inset-top))',
      }"
    >
      <section class="header-box w-full shadow flex" style="z-index: 2">
        <div class="w-full px-5 py-2">
          <div class="flex justify-between items-center">
            <div class="text-base">
              {{ /*选择提及人员*/ qLangComment.toSelectMentions }}
            </div>
            <t-icon
              name="close"
              size="16px"
              @click="selfVisible = false"
            ></t-icon>
          </div>

          <!-- 输入查询 -->
          <div class="flex items-center w-full py-2 no-wrap">
            <div class="flex-1 relative flex items-center">
              <!-- 搜索图标 -->
              <t-icon
                name="search"
                size="16px"
                class="teld-color-gray pointer-events-none absolute"
                style="left: 12px; top: 12px"
              ></t-icon>
              <!-- 清空图标 -->
              <t-icon
                v-show="keyword"
                name="close"
                size="16px"
                class="teld-color-gray cursor-pointer absolute"
                style="right: 12px; top: 12px"
                @click="onClearInput"
              ></t-icon>
              <span
                v-show="!keyword"
                class="placeholder text-sm absolute teld-color-gray pointer-events-none"
                style="left: 32px"
                >{{
                  /** 搜索姓名、账户、邮箱、手机号 */
                  qLangComment.inputNameAccountMailPhoneToSearch
                }}</span
              >
              <!-- 模拟的输入框 -->
              <div
                ref="keywordRef"
                class="px-2 py-2 flex-1 rounded teld-bg-color-gray van-ellipsis"
                contenteditable
                style="outline: none; min-height: 32px; padding-left: 32px"
                @paste="onPaste"
                @input="onInput"
                @keydown.enter.prevent
                @focus="onFocus"
              >
              </div>
            </div>
            <!-- 搜索 -->
            <!-- <label class="ml-2 teld-theme-color" @click="onClickSearch">{{
              qLangComment.search
            }}</label> -->
          </div>
        </div>
      </section>

      <div class="w-full flex-1 pl-5 outline-none overflow-hidden">
        <!-- 未搜索时显示最近提及人员 -->
        <div v-show="!keyword" class="w-full h-full overflow-auto q-pr-md">
          <div class="teld-color-gray q-py-md sticky top-0 bg-white z-1">
            {{
              recentlyMentionedUsers.length
                ? qLangComment.recentlyMentions /** 最近提及人员 */
                : qLangComment.noRecentlyMentions /*暂无最近提及的人员，输入人名进行搜索*/
            }}
          </div>
          <personnel-item
            v-for="(item, index) in recentlyMentionedUsers"
            :key="item.UserID"
            :data-item-index="index"
            v-model:data-item="recentlyMentionedUsers[index]"
            class="flex items-center pt-4"
            :style="{ 'padding-top': index === 0 ? 0 : null }"
          ></personnel-item>
        </div>

        <!-- 搜索结果 -->
        <div v-if="!!keyword">
          <t-repeat
            ref="repeatRef"
            v-model:list="userList"
            fill-margin-bottom="64px"
            :auto-load="false"
            :emptyText="qLangComment.noData"
            class="q-pt-md q-pr-md"
            @scroll-load="onScrollLoad"
          >
            <template #default>
              <personnel-item
                v-for="(item, index) in userList"
                :key="item.UserID"
                :keyword="keyword"
                :match-field="matchField"
                :data-item-index="index"
                v-model:data-item="userList[index]"
                class="flex items-center pt-4"
                :style="{ 'padding-top': index === 0 ? 0 : null }"
              >
              </personnel-item>
            </template>
          </t-repeat>
        </div>
      </div>

      <section class="footer-box w-full shadow-2 flex items-center py-4 px-5">
        <t-button
          :label="qLangComment.confirmNo"
          class="tr-button-default flex-1 mr-3"
          size="md"
          style="height:40px;font-size:16px;"
          @click="selfVisible = false"
        ></t-button>

        <t-button
          :label="qLangComment.confirmYes"
          class="tr-button-default flex-1"
          color="primary"
          size="md"
          style="height:40px;font-size:16px;"
          :disable="!selected.length"
          @click="onConfirm"
        ></t-button>
      </section>
    </div>
  </t-dialog>
</template>

<script setup>
// Components
import UserAvatar from '../../components/user-avatar/index.vue';
import GenderFemale from '../../components/svg-icons/gender-female.vue';
import GenderMale from '../../components/svg-icons/gender-male.vue';
import HighlightSearchResult from '../../components/HighlightSearchResult/index.vue';
import personnelItem from './personnel-item.vue';

// Utils
import { ref, reactive, computed, watch, inject, nextTick } from 'vue';
import usePasteText from '../../hooks/usePasteText';

// Utils
import { getRangeRect, debounce } from '../../hooks';
import { TELD_ORG_ID, SG_USER_LIST_QUERY_FIELDS } from '../../utils';
import { getSysCommonUserList } from '../../hooks/api.js';

const KEYWORD_MAX_LENGTH = 20;

const qLangComment = inject('qLangComment');
const _recentlyMentionedUsers_ = inject('recentlyMentionedUsers', []);
const recentlyMentionedUsers = ref([]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(['update:visible', 'selected']);
const selfVisible = computed({
  get() {
    return props.visible;
  },
  set(v) {
    emit('update:visible', v);
  },
});
const loading = ref(false);
const userList = ref([]);
const keyword = ref('');
const keywordRef = ref();
const repeatRef = ref();
const matchField = ref(SG_USER_LIST_QUERY_FIELDS.REAL_NAME);

const currentList = computed(() => {
  return keyword.value ? userList.value : recentlyMentionedUsers.value;
});
const selected = computed(() => {
  return currentList.value.filter(n => n._checked_);
});

const onFocus = () => {
  // 为了兼容移动端Edge浏览器问题：1.设最大高度 2.焦点输入框滚动进入可见区域
  keywordRef.value.scrollIntoView();
};
watch(selfVisible, (v) => {
  setTimeout(() => {
    v && keywordRef.value.focus();
  });
});

const onBeforeShow = () => {
  recentlyMentionedUsers.value = _recentlyMentionedUsers_.value.map(n => {
    return {
      ...n,
      _checked_: false,
    };
  });
};
const onHide = () => {
  userList.value = [];
  keyword.value = '';
};

const onPaste = e => {
  const pasteText = usePasteText(e);
};
const onInput = e => {
  // 保存当前光标位置
  const selection = window.getSelection();
  const range = selection.getRangeAt(0);
  const startOffset = range.startOffset;
  const endOffset = range.endOffset;
  const isCollapsed = range.collapsed;

  const text = (e.target.textContent || '').trim();
  if (text.length > KEYWORD_MAX_LENGTH) {
    e.target.textContent = text.slice(0, KEYWORD_MAX_LENGTH);

    // 如果重新给文本赋值后，光标位置会回到开头，这里保持光标位置
    nextTick(() => {
      if (startOffset > keyword.value.length) {
        range.setStart(e.target.firstChild, keyword.value.length);
        range.setEnd(e.target.firstChild, keyword.value.length);
      } else {
        range.setStart(e.target.firstChild, startOffset);
        range.setEnd(e.target.firstChild, startOffset);
      }
    });
  }
  keyword.value = e.target.textContent.trim();
  if (!keyword.value) {
    userList.value = [];
  }

  reloadSearch();
};

const onClearInput = () => {
  keywordRef.value.textContent = keyword.value = '';
  userList.value = [];
};

const reloadSearch = debounce(async () => {
  if (!keyword.value) {
    return;
  }
  if (loading.value) {
    setTimeout(() => {
      reloadSearch();
    }, 500);
    return;
  }
  repeatRef.value.reload();
}, 600);

/**
 * @summary User姓名下的附加信息
 * - DutyID 就是职位，这接口字段也太不讲究了
 * - 公司部门信息：[CompanyName, DepartmentName, WorkgroupName]
 * @param {Object} item
 */
const combinedDepartmentInfo = item => {
  const { CompanyName, DepartmentName, WorkgroupName } = item;
  return [CompanyName, DepartmentName, WorkgroupName]
    .filter(n => !!n)
    .join('-');
};

const onScrollLoad = async (index, size, done) => {
  try {
    const { total, rows } = await loadList(index, size);
    userList.value = userList.value.concat(rows);
    // 获取完数据，必须调用 done 函数，传入是否数据已全部加载
    done({ stop: total <= userList.value.length, totalCount: total });
  } catch (error) {
    console.log(error);
  }
};

/** 获取用户数据列表 */
const loadList = async (pageIndex, pageSize) => {
  loading.value = true;
  const fieldName = getKeyFiled(keyword.value);
  const ret = { rows: [], total: 0 };

  const payload = {
    // FieldName: 'RealName',
    FieldName: fieldName,
    FieldValue: keyword.value,
    FilterKey: {
      Data_FunctionID: 'DF686BBF-2387-4259-886B-249022156A8A',
      Enabled: 1,
      FilterByPeakOrgID: TELD_ORG_ID,
      NoDataAuth: 'true',
    },
    page: pageIndex,
    rows: pageSize,
  };

  try {
    // const { data } = await this.$utils.sgApi.getDataAsync({
    //   url: this.$utils.common.getServiceUrl(
    //     'SYS_CommonHelper_GetUserList&help=true',
    //   ),
    //   method: 'POST',
    //   data: { filter: JSON.stringify(payload) },
    // });
    const res = await getSysCommonUserList(payload);

    if (!res) {
      return ret;
    }
    const { total, rows } = res;
    Object.assign(ret, {
      total,
      rows: rows.map(n => {
        return {
          ...n,
          _checked_: false,
        };
      }),
    });
  } catch (error) {
    console.log(error);
  } finally {
    return new Promise(resolve => {
      setTimeout(() => {
        loading.value = false;
        resolve(ret);
      }, 500);
    });
  }
};

/** 防抖后的loadList */
const debouncedLoadList = debounce(loadList, 500);

const getKeyFiled = val => {
  // const regExpCName = /[\\u4E00-\\u9FFF]+/g;
  const regExpCName = /^[\u4E00-\u9FFF]+$/;
  // 正则识别邮箱：不是要验证邮箱是否合法，而是用于搜索时，识别到输入的是邮箱，即使还没输入完整
  // const regExpEmail = /^[a-z0-9_.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]+)$/i;
  const regExpEmail = /^[a-z0-9_.-]+@[a-z0-9-]*(\.[a-z0-9-]*)*(\.[a-z]*){0,}$/i;
  const regExpPhone = /^\d+$/; // 不固定位数因为手机号支持模糊查询
  matchField.value = SG_USER_LIST_QUERY_FIELDS.REAL_NAME;

  if (regExpCName.test(val)) {
    matchField.value = SG_USER_LIST_QUERY_FIELDS.REAL_NAME;
  } else if (regExpEmail.test(val)) {
    matchField.value = SG_USER_LIST_QUERY_FIELDS.EMAIL;
  } else if (regExpPhone.test(val)) {
    matchField.value = SG_USER_LIST_QUERY_FIELDS.MOBILE;
  } else {
    matchField.value = SG_USER_LIST_QUERY_FIELDS.ACCOUNT;
  }
  return matchField.value;
};

// const onClickSearch = () => {
//   userList.value = [];
//   if (repeatRef.value) {
//     repeatRef.value.reload();
//   } else {
//     searched.value = true;
//   }
// };

const onConfirm = () => {
  selfVisible.value = false;
  emit('selected', selected.value);
};
</script>
